package com.pet.serve.service;

import com.pet.serve.entity.Schedule;
import com.pet.serve.repository.ScheduleRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.Date;
import java.util.List;

@Service
public class ScheduleService {


    private final ScheduleRepository scheduleRepository;

    public ScheduleService(ScheduleRepository scheduleRepository) {
        this.scheduleRepository = scheduleRepository;
    }

    //添加新的日程
    public Schedule addSchedule(Schedule schedule) {
        schedule.setCreateTime(new Date());
        schedule.setUpdateTime(new Date());
        return scheduleRepository.save(schedule);
    }

    // 更新日程
    public Schedule updateSchedule(Schedule schedule) {
        Schedule existingSchedule = scheduleRepository.findById(schedule.getScheduleid())
                .orElseThrow(() -> new IllegalArgumentException("Invalid schedule ID"));
        existingSchedule.setTextarea(schedule.getTextarea());
        existingSchedule.setUpdateTime(new Date());
        return scheduleRepository.save(existingSchedule);
    }

    // 根据ID删除日程
    public void deleteSchedule(Long scheduleId) {
        scheduleRepository.deleteById(scheduleId);
    }

    // 根据用户名删除日程
    @Transactional
    public void deleteSchedulesByUsername(String username) {
        scheduleRepository.deleteByUsername(username);
    }

    // 根据ID批量删除日程
    @Transactional
    public void deleteSchedulesByIds(List<Long> scheduleIds) {
        scheduleRepository.deleteByScheduleidIn(scheduleIds);
    }

    // 根据用户名查找日程
    public List<Schedule> getSchedulesByUsername(String username) {
        return scheduleRepository.findByUsername(username);
    }

    // 根据日期查找日程
    public List<Schedule> getSchedulesByDay(Date day) {
        return scheduleRepository.findByDay(day);
    }

    // 根据日期范围查找日程
    public List<Schedule> getSchedulesBetweenDates(Date startDate, Date endDate) {
        return scheduleRepository.findByDayBetween(startDate, endDate);
    }

    // 分页查找所有日程
    public List<Schedule> getAllSchedules(int pageNo, int pageSize) {
        PageRequest pageable = PageRequest.of(pageNo, pageSize);
        Page<Schedule> page = scheduleRepository.findAll(pageable);
        return page.getContent();
    }


}
